package com.budwk.app.miniapp.controllers.admin;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.miniapp.models.WxUser;
import com.budwk.app.miniapp.services.WxUserAuthService;
import com.budwk.app.miniapp.utils.HttpUtils;
import com.budwk.app.miniapp.utils.JwtUtil;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.*;

@IocBean
@At("/platform/miniapp/user/auth")
@ApiDefinition(tag = "微信小程序-用户认证")
@Slf4j
public class WxUserAuthController {

    @Inject
    private WxUserAuthService wxUserAuthService;

    /**
     * 小程序用户登录
     *
     * @param loginCode 登录code
     * @param phoneCode 获取手机的 code
     * @param phone     手机号
     * @return
     */
    @At("/wxlogin")
    @Ok("json:full")
    @GET
    @ApiOperation(name = "小程序用户登录")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "loginCode", description = "登陆码"),
                    @ApiFormParam(name = "phoneCode", description = "手机验证码"),
                    @ApiFormParam(name = "phone", description = "电话号码"),
                    @ApiFormParam(name = "appType", description = "应用类型")
            }
    )
    public Result<?> wxlogin(@Param("loginCode") String loginCode,
                             @Param("phoneCode") String phoneCode,
                             @Param("phone") String phone,
                             @Param("appType") String appType) {
        WxUser vo = new WxUser();
        try {
            if (loginCode == null || appType == null) {
                return Result.error("loginCode或者appType为空！");
            }
            vo = wxUserAuthService.wxLogin(loginCode, phoneCode, phone, appType);

            SaSession session = StpUtil.getSession(true);
            session.set("id", Strings.sNull(vo.getId()));
            session.set("loginname", Strings.sNull(vo.getPhone()));
            session.set("username", Strings.sNull(vo.getPhone()));
            session.set("phone", Strings.sNull(vo.getPhone()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
        return Result.success(vo);
    }


    @At("/refreshToken")
    @Ok("json")
    @POST
    public Result<?> refreshToken(@Param("refreshToken") String refreshToken) {
       if(!JwtUtil.validate(refreshToken)) {
           return Result.error(600099,"refreshToken失效");
       }
        return Result.success(wxUserAuthService.refreshToken(refreshToken));
    }
    /**
     * 获取用户绑定手机号信息
     */
    @At("/getPhone")
    @Ok("json")
    @GET
    @ApiOperation(name = "获取用户绑定手机号码")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "appid", description = "唯一标识", required = true, check = true),
                    @ApiFormParam(name = "code")
            }
    )
    public Result<?> getPhone(String appid, String code) {
        String secret = "18f7c874366e9c4109a0247a6090b132";
        if (appid == null) {
            appid = "wxe8c4e2060ad7715a";
        }
        String accessToken = "";
        String phoneNumber = "";
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            String loginresult = HttpUtils.getRequest(url);

            JSONObject jsonObject = JSONObject.parseObject(loginresult);
            accessToken = jsonObject.getString("access_token");

        } catch (Exception e) {
            System.out.println("获取access_token异常" + e.getMessage());
        }
        try {
            //用 access_token + code 获取手机号
            JSONObject jsonCode = new JSONObject();
            jsonCode.put("code", code);
            String resPhone = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, jsonCode.toString());
            if (StringUtils.isEmpty(resPhone) || !resPhone.contains("phone_info") || !resPhone.contains("phoneNumber")) {
                System.out.println("微信官方修改了小程序获取用户手机号码相关接口！");
            }
            JSONObject resPhoneInfo = JSON.parseObject(resPhone);
            JSONObject phoneInfo = resPhoneInfo.getJSONObject("phone_info");
            return Result.success(phoneInfo);
        } catch (Exception e) {
            System.out.println("获取手机号异常" + e.getMessage());
            return Result.success("获取手机号异常" + e.getMessage());
        }
    }


    /**
     * <pre>
     * 获取用户登录的access_token
     * </pre>
     */
    @At("/getAccessToken")
    @Ok("json")
    @GET
    @ApiOperation(name = "获取用户登录的access_token")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "appid", description = "唯一标识", required = true, check = true)
            }
    )
    public Result<?> getAccessToken(String appid) {

        String secret = "18f7c874366e9c4109a0247a6090b132";
        if (appid == null) {
            appid = "wxe8c4e2060ad7715a";
        }
        String accessToken = "";
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            String loginresult = HttpUtils.getRequest(url);

            JSONObject jsonObject = JSONObject.parseObject(loginresult);
            accessToken = jsonObject.getString("access_token");

        } catch (Exception e) {
            System.out.println("获取access_token异常" + e.getMessage());
        }
        return Result.success(accessToken);
    }
}
